#include "stdafx.h"

#include "framebuffer.h"
#include "ARB_extensions.h"

CFrameBufferObject::CFrameBufferObject(const SRect & rect) : _texID(0), _fbID(0), _depth_rbID(0), _vp(rect)
{
	glGenTextures(1, &_texID);
	glBindTexture(GL_TEXTURE_2D, _texID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, rect.w, rect.h, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);

	glGenFramebuffersEXT(1, &_fbID);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbID);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, _texID, 0);

	glGenRenderbuffersEXT(1, &_depth_rbID);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _depth_rbID);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, 256, 256);

	// Set up _texID and _depth_rbID for render-to-texture
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, _texID, 0);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, _depth_rbID);

	//Does the GPU support current FBO configuration?
	if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT)
	{
//		throw stuff;
	}
	glBindTexture(GL_TEXTURE_2D, 0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

void CFrameBufferObject::enable()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbID);
	_vp.activate();

	/*
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	//-------------------------
	glViewport(0, 0, 256, 256);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0.0, 256.0, 0.0, 256.0, -1.0, 1.0); 
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	//-------------------------
//	glDisable(GL_TEXTURE_2D);
//	glDisable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);
*/

}

void CFrameBufferObject::release()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
//	glBindTexture(GL_TEXTURE_2D, _texID);
}